package net.woggle.shackbrowse.notifier;

import net.woggle.shackbrowse.CacheSeenSearch;
import net.woggle.shackbrowse.MainActivity;
import net.woggle.shackbrowse.R;

import com.commonsware.cwac.wakeful.WakefulIntentService;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

public class NotifierReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.i("SBNOTIFIER", "NotifierReceiver invoked, starting service");

      
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
      /*
      AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
      PendingIntent pendingIntent =
               PendingIntent.getBroadcast(context, 0, new Intent(context, NotifierReceiver.class), 0);

      // use inexact repeating which is easier on battery (system can phase events and not wake at exact times)
      alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0,
    		  AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
      */
		Bundle data = intent.getExtras();
		if (data != null)
		{
			if (data.getString("type").equalsIgnoreCase("reply"))
			{
			  
				NotificationCompat.Builder mBuilder =
				        new NotificationCompat.Builder(context)
				        .setSmallIcon(R.drawable.icon)
				        .setContentTitle(data.getString("username") + " replied to your post")
						.setContentText(data.getString("text"))
						.setTicker(data.getString("username") + " replied to your post")
						.setAutoCancel(true);
				
				
				// Creates an explicit intent for an Activity in your app
				Intent resultIntent = new Intent(context, MainActivity.class);
				
				resultIntent.putExtra("notificationOpenId", true);
				resultIntent.putExtra("notificationNLSID", Integer.parseInt(data.getString("nlsid")));
				
				// we need to check if a notification already exists
				String lastNotifiedId = prefs.getString("GCMLastNotifiedId", "0");
				String lastClickedId = prefs.getString("GCMLastClickedId", "0");
	
				// second if checks if we are replacing a notification when the last one was never clicked
				// if so must create a multi reply
				if ((data.getString("username").equals("multiple")) || (!lastClickedId.equals(lastNotifiedId)))
				{
					// multiple replies
					mBuilder.setContentTitle("New Replies");
					mBuilder.setContentText("Click to show a list");
					int numNew = 0;
					if (data.getString("username").equals("multiple"))
					{
						try {
							numNew = Integer.parseInt(data.getString("text"));
						}
						catch (Exception e)
						{
							
						}
						mBuilder.setNumber(numNew);
					}
					if (numNew == 0)
						mBuilder.setTicker("New replies to your posts");
					else
						mBuilder.setTicker(numNew + " new replies to your posts");
					
					resultIntent.putExtra("notificationOpenParentAuthorSearch", true);
					
				}
				
				resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
				
				// stupid hack for android bug
				resultIntent.setAction(Long.toString(System.currentTimeMillis()));
				
				PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
				
				mBuilder.setContentIntent(resultPendingIntent);
				Notification notification = mBuilder.build();
				
				int mId = 58401;
				handleNotification(notification, mId, context);
				
				Editor editor = prefs.edit();
				editor.putString("GCMLastNotifiedId", data.getString("id"));
				editor.commit();
			}
			else if (data.getString("type").equalsIgnoreCase("vanity"))
			{
			  
				NotificationCompat.Builder mBuilder =
				        new NotificationCompat.Builder(context)
				        .setSmallIcon(R.drawable.icon)
				        .setContentTitle(data.getString("username") + " mentioned you in a post")
						.setContentText(data.getString("text"))
						.setTicker(data.getString("username") + " mentioned you in a post")
						.setAutoCancel(true);
				
				
				// Creates an explicit intent for an Activity in your app
				Intent resultIntent = new Intent(context, MainActivity.class);
				
				resultIntent.putExtra("notificationOpenVanityId", true);
				resultIntent.putExtra("notificationNLSID", Integer.parseInt(data.getString("nlsid")));
				
				// we need to check if a notification already exists
				String lastNotifiedId = prefs.getString("GCMVanityLastNotifiedId", "0");
				String lastClickedId = prefs.getString("GCMVanityLastClickedId", "0");
	
				// second if checks if we are replacing a notification when the last one was never clicked
				// if so must create a multi reply
				if ((data.getString("username").equals("multiple")) || (!lastClickedId.equals(lastNotifiedId)))
				{
					// multiple replies
					mBuilder.setContentTitle("New Mentions of You");
					mBuilder.setContentText("Click to show a list");
					int numNew = 0;
					if (data.getString("username").equals("multiple"))
					{
						try {
							numNew = Integer.parseInt(data.getString("text"));
						}
						catch (Exception e)
						{
							
						}
						mBuilder.setNumber(numNew);
					}
					mBuilder.setTicker(numNew + " new mentions of your shack name");
					
					resultIntent.putExtra("notificationOpenVanitySearch", true);
					
				}
				
				resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
				
				// stupid hack for android bug
				resultIntent.setAction(Long.toString(System.currentTimeMillis()));
				
				PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
				
				mBuilder.setContentIntent(resultPendingIntent);
				Notification notification = mBuilder.build();
				
				int mId = 58402;
				handleNotification(notification, mId, context);
				
				Editor editor = prefs.edit();
				editor.putString("GCMVanityLastNotifiedId", data.getString("id"));
				editor.commit();
			}
			else if (data.getString("type").equalsIgnoreCase("shackmsg"))
			{
			  
				NotificationCompat.Builder mBuilder =
				        new NotificationCompat.Builder(context)
				        .setSmallIcon(R.drawable.icon)
				        .setContentTitle(data.getString("username") + " sent you a shackmessage")
						.setContentText(data.getString("text"))
						.setTicker(data.getString("username") + " sent you a shackmessage")
						.setAutoCancel(true);
				
				
				// Creates an explicit intent for an Activity in your app
				Intent resultIntent = new Intent(context, MainActivity.class);
				
				resultIntent.putExtra("notificationOpenMessages", true);
				resultIntent.putExtra("notificationNLSID", Integer.parseInt(data.getString("nlsid")));
				
				// we need to check if a notification already exists
				String lastNotifiedId = prefs.getString("GCMShackMsgLastNotifiedId", "0");
				String lastClickedId = prefs.getString("GCMShackMsgLastClickedId", "0");
	
				if (data.getString("username").equals("multiple"))
				{
					// multiple replies
					mBuilder.setContentTitle("New shackmessages");
					mBuilder.setContentText("Click to show a list");
					int numNew = 0;
					if (data.getString("username").equals("multiple"))
					{
						try {
							numNew = Integer.parseInt(data.getString("text"));
						}
						catch (Exception e)
						{
							
						}
						mBuilder.setNumber(numNew);
					}
					mBuilder.setTicker(numNew + " new shackmessages");
					
					resultIntent.putExtra("notificationOpenMessages", true);
					
				}
				
				resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
				
				// stupid hack for android bug
				resultIntent.setAction(Long.toString(System.currentTimeMillis()));
				
				PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
				
				mBuilder.setContentIntent(resultPendingIntent);
				Notification notification = mBuilder.build();
				
				int mId = 58403;
				handleNotification(notification, mId, context);
				
				Editor editor = prefs.edit();
				editor.putString("GCMShackMsgLastNotifiedId", data.getString("id"));
				editor.commit();
			}
		}
   }

	private void handleNotification(Notification notification, int mId, Context context) {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		
		NotificationManager mNotificationManager =
		    (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		
		notification.sound = Uri.parse(prefs.getString("notificationSound", "DEFAULT_SOUND"));
		
		if (prefs.getBoolean("notificationVibrate", true))
			notification.defaults|= Notification.DEFAULT_VIBRATE;
		notification.flags |= Notification.FLAG_SHOW_LIGHTS;
		notification.ledARGB = Color.GREEN;
		notification.ledOffMS = 1500;
		notification.ledOnMS = 100;
		// mId allows you to update the notification later on.
		
		mNotificationManager.notify(mId, notification);
            	
		// WakefulIntentService.sendWakefulWork(context, new Intent(context, NotifierService.class));
		setResultCode(Activity.RESULT_OK);
		
	}
}